package com.gexiaobao.pigeon.ui.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.widget.AppCompatImageView
import androidx.recyclerview.widget.RecyclerView
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia

/**
 * @author：luck
 * @date：2016-7-27 23:02
 * @describe：GridImageAdapter
 */
class UploadImageAdapter(context: Context?, result: List<LocalMedia>?) : RecyclerView.Adapter<UploadImageAdapter.ViewHolder>() {

    private val mInflater: LayoutInflater
    val data = ArrayList<LocalMedia>()
    var selectMax = 3
    private var mIntentType: Int = 0
    var checkPos: Int = 0

    /**
     * 删除
     */
    fun delete(position: Int) {
        try {
            if (position != RecyclerView.NO_POSITION && data.size > position) {
                data.removeAt(position)
                notifyItemRemoved(position)
                notifyItemRangeChanged(position, data.size)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun remove(position: Int) {
        if (position < data.size) {
            data.removeAt(position)
        }
    }

    fun setIntentType(type: Int) {
        this.mIntentType = type
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var mImg: ImageView
        var mIvDel: ImageView
        var ivCheckedBloodImage: AppCompatImageView
        var llItemBloodCoverImage: LinearLayout

        init {
            mImg = view.findViewById(R.id.ivItemProofPicture)
            mIvDel = view.findViewById(R.id.iv_del)
            ivCheckedBloodImage = view.findViewById(R.id.ivCheckedBloodImage)
            llItemBloodCoverImage = view.findViewById(R.id.llItemBloodCoverImage)
        }
    }

    override fun getItemCount(): Int {
        return if (data.size < selectMax) {
            data.size + 1
        } else {
            data.size
        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (isShowAddItem(position)) {
            TYPE_CAMERA
        } else {
            TYPE_PICTURE
        }
    }

    /**
     * 创建ViewHolder
     */
    override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ViewHolder {
        val view = mInflater.inflate(R.layout.upload_image, viewGroup, false)
        return ViewHolder(view)
    }

    private fun isShowAddItem(position: Int): Boolean {
        val size = data.size
        return position == size
    }

    /**
     * 设置值
     */
    override fun onBindViewHolder(viewHolder: ViewHolder, @SuppressLint("RecyclerView") position: Int) {
        //少于MaxSize张，显示继续添加的图标
        if (getItemViewType(position) == TYPE_CAMERA) {
            viewHolder.mImg.setImageResource(R.drawable.add_img)
            viewHolder.mImg.setOnClickListener {
                if (mItemClickListener != null) {
                    mItemClickListener!!.openPicture()
                }
            }
            viewHolder.mIvDel.visibility = View.INVISIBLE
            viewHolder.llItemBloodCoverImage.visibility = View.INVISIBLE
        } else {
            data[position].isChecked = checkPos == position
            viewHolder.llItemBloodCoverImage.visibility = View.VISIBLE
            viewHolder.mIvDel.visibility = View.VISIBLE
            viewHolder.mIvDel.setOnClickListener {
                val index = viewHolder.absoluteAdapterPosition
                if (index != RecyclerView.NO_POSITION && data.size > index) {
                    mItemClickListener!!.onDeleteImage(index)
                    data.removeAt(index)
                    notifyItemRemoved(index)
                    notifyItemRangeChanged(index, data.size)
                }
            }
            val media = data[position]
            val path = media.availablePath
            if (mIntentType == 2 || mIntentType == 3) {
                ImageLoaderManager.loadRoundImage(
                    viewHolder.itemView.context,
                    (if (media.imageUrl == null) ((if (PictureMimeType.isContent(path) && !media.isCut && !media.isCompressed) Uri.parse(path) else path).toString()) else media.imageUrl),
                    viewHolder.mImg,
                    12
                )
            } else {
                val chooseModel = media.chooseModel
                if (chooseModel == SelectMimeType.ofAudio()) {
                    viewHolder.mImg.setImageResource(R.drawable.ps_audio_placeholder)
                } else {
                    ImageLoaderManager.loadRoundImage(
                        viewHolder.itemView.context,
                        ((if (PictureMimeType.isContent(path) && !media.isCut && !media.isCompressed) Uri.parse(path) else path).toString()),
                        viewHolder.mImg,
                        12
                    )
                }
            }
            //itemView 的点击事件
            if (mItemClickListener != null) {
                viewHolder.itemView.setOnClickListener { v: View? ->
                    val adapterPosition = viewHolder.absoluteAdapterPosition
                    mItemClickListener!!.onItemClick(v, adapterPosition)
                }
            }

            val reason = data[position]
            if (reason.isChecked) {
                viewHolder.ivCheckedBloodImage.setImageResource(R.mipmap.icon_checkbox_checked)
            } else {
                viewHolder.ivCheckedBloodImage.setImageResource(R.mipmap.icon_checkbox_unchecked)
            }

            viewHolder.llItemBloodCoverImage.setOnClickListener {
//                if (checkPos != position) {
                //取消上一个位置的勾选状态
                if (checkPos != -1) {
                    data[checkPos].isChecked = false
                    notifyItemChanged(checkPos)
                }
                //设置新的勾选状态
                checkPos = position
                data[checkPos].isChecked = true
                notifyItemChanged(checkPos)
//                }
                mItemClickListener!!.onCoverChecked(checkPos)
            }
        }
    }

    private var mItemClickListener: OnItemClickListener? = null
    fun setOnItemClickListener(l: OnItemClickListener?) {
        mItemClickListener = l
    }

    interface OnItemClickListener {
        /**
         * Item click event
         *
         * @param v
         * @param position
         */
        fun onItemClick(v: View?, position: Int)

        /**
         * Open PictureSelector
         */
        fun openPicture()

        /**
         * Cover Picture Selector
         */
        fun onCoverChecked(position: Int)

        /**
         * delete Picture
         */
        fun onDeleteImage(index: Int)
    }

    init {
        mInflater = LayoutInflater.from(context)
        data.addAll(result!!)
    }

    companion object {
        const val TAG = "gexiaobao"
        const val TYPE_CAMERA = 1
        const val TYPE_PICTURE = 2
    }
}
